package com.taobao.txc.sample;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.jdbc.core.JdbcTemplate;

@SpringBootApplication
@EnableFeignClients
public class Application implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);

    @Autowired
    private BizService bizService;

    @Autowired
    private JdbcTemplate jdbcTemplateA;

    @Autowired
    private JdbcTemplate jdbcTemplateB;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        int balanceA = jdbcTemplateA.queryForObject("select money from user_money_a where id = 1", java.lang.Integer.class);
        int balanceB = jdbcTemplateB.queryForObject("select money from user_money_b where id = 1", java.lang.Integer.class);
        LOGGER.info("Before transfer! A: " + balanceA + "   B: " + balanceB + "   total：" + (balanceA + balanceB));
        LOGGER.info("--------------------------------------------------------------------------------------------");

        for (int i = 1; i <= 100; ++i) {
            LOGGER.info("Transfer[" + i + "] begins ...");
            try {
                bizService.doTransfer(300);
                LOGGER.info("Transfer[" + i + "] is done! ");
            } catch (Exception e) {
                LOGGER.info("Transfer[" + i + "] failed since " + e.getMessage() + ". Money is rolled back.");
            }
            balanceA = jdbcTemplateA.queryForObject("select money from user_money_a where id = 1", java.lang.Integer.class);
            balanceB = jdbcTemplateB.queryForObject("select money from user_money_b where id = 1", java.lang.Integer.class);
            LOGGER.info("Let's check! A: " + balanceA + "   B: " + balanceB + "   total：" + (balanceA + balanceB));
            LOGGER.info("--------------------------------------------------------------------------------------------");
        }
    }
}
